<template>
    <div style="width: 100%; height: 100%; display: flex; flex-direction: column; padding: 5rem 14rem" v-loading="isloading">
        <div style="flex: 1;overflow: auto;" :class="{ 'filter-5': isloading }">
            <div id="typingEffect" style="font-size: 3.6rem;line-height: 7.2rem;white-space: pre-wrap;word-break: break-word">
                <template v-for="(item, index) in paragraph">
                    <template v-if="item.text !== 'line-feed'">
                        <span v-if="item.sign" :key="item.id" style="color:#1abc9c">{{ `${item.text} ` }}</span>
                        <template v-else>{{ `${item.text} ` }}</template>
                    </template>
                    <!-- <div style="height: 3rem;width: 100%" v-else></div> -->
                </template>
            </div> 
        </div>
        <div style="display: flex; justify-content: flex-end;padding-top: 2rem;">
            <el-button v-loading="confirmLoading" @click="toArticlePage" style="width: 16rem;font-size:2rem;padding: 1.1rem 3rem;" type="primary" :disabled="isloading">  
                <div class="flex_c_c cur">开始阅读学习</div> 
            </el-button>
        </div>
    </div>
</template>

<script>
import { getToken } from '@/utils/storage'
import { exerciseInfo, startExercise } from '@/api/articleExercise.js'
import config from '@/config/index.js'
export default {
    components: {},
    data() {
        return {
            ws: null,
            loading: false,
            isloading: false,
            confirmLoading: false,
            userId: '',
            exerciseId: '',
            exercise: {},
            requestQuery: {},
            aiContentItems: {
                // 预先定义,用于解决VUE2响应式BUG
                'Paragraph-1': [],
                'Paragraph-2': [],
                'Paragraph-3': [],
                'Paragraph-4': [],
                'Paragraph-5': [],
                'Paragraph-6': [],
                'Paragraph-7': [],
                'Paragraph-8': [],
                'Paragraph-9': [],
                'Paragraph-10': [],
                'Paragraph-11': [],
                'Paragraph-12': [],
                'Paragraph-13': [],
                'Paragraph-14': [],
                'Paragraph-15': [],
                'Paragraph-16': [],
                'Paragraph-17': [],
                'Paragraph-18': [],
                'Paragraph-19': [],
                'Paragraph-20': [],
                'Paragraph-21': [],
                'Paragraph-22': [],
                'Paragraph-23': [],
                'Paragraph-24': [],
                'Paragraph-25': [],
                'Paragraph-26': [],
                'Paragraph-27': [],
                'Paragraph-28': [],
                'Paragraph-29': [],
                'Paragraph-30': []
            },
            aiTranslationItems: [],
            separatorCount: 0,
            socketIndex: 0,
            socketLoading: true,
            courseArticle: {},
            timeoutIndex: 0,
            keylist: [],
            keystring: '',
            timerIndex: 0,
            paragraph: [],
        }
    },
    created() {
        let requestQuery = window.sessionStorage.getItem("aireading-word-next-page-request-query");
        requestQuery = JSON.parse(requestQuery);
        this.requestQuery = requestQuery;
        this.userId = requestQuery.userId
        this.exerciseId = requestQuery.exerciseId
        this.initWebSocket();
    },
    mounted() {
    },
    // watch: {
    //     aiContentItems: {
    //         deep: true,
    //         handler(newVal, oldVal) {
    //         }
    //     }
    // },
    methods: {
        getExercise() {
            this.loading = true
            exerciseInfo({ id: this.exerciseId, userId: this.userId }).then(res => {
                this.loading = false
                this.exercise = res.data;
                if (this.ws) {
                    const data = {
                        type: 'chat',
                        payload: {
                            type: 1,
                            words: this.requestQuery.words,
                            userId: this.requestQuery.userId,
                            courseId: this.requestQuery.courseId,
                            learnId: this.requestQuery.learnId || 0,
                            sourceType: 2
                        }
                    };
                    this.ws.send(JSON.stringify(data));
                }
            }).finally(() => {
                this.loading = false
            })
        },
        closeWebSocket() {
            if (this.ws) {
                // 移除所有事件监听
                this.ws.onclose = null;
                this.ws.onerror = null;
                this.ws.onmessage = null;
                this.ws.onopen = null;
                
                // 如果连接还开着就关闭它
                if (this.ws.readyState === WebSocket.OPEN) {
                    this.ws.close();
                }
                this.ws = null;
            }
        },
        initWebSocket() {
            // 确保之前的连接已经关闭
            this.closeWebSocket();
            
            const that = this;
            this.isloading = true;
            this.socketLoading = true;
            this.separatorCount = 0;
            
            // 修改 WebSocket 连接地址
            const SOCKET_URL = process.env.NODE_ENV === 'development' 
                ? '/api/hunyuan'  // 使用相对路径，通过代理访问
                : 'wss://study.bjzhihuiguo.com/api/hunyuan';
            
            // 获取 token 并确保格式正确
            const token = getToken('T_TOKEN');
            const cleanToken = token ? token.replace('Bearer ', '') : '';
            const authToken = cleanToken ? `Bearer ${cleanToken}` : '';
            
            try {
                // 创建 WebSocket 连接
                this.ws = new WebSocket(SOCKET_URL + '?token=' + encodeURIComponent(authToken));
                
                // 添加连接状态日志
                console.log('Connecting to WebSocket with token:', authToken);
                
                this.ws.onopen = function () {
                    console.log('WebSocket连接成功');
                    if (that.exerciseId) {
                        that.getExercise();
                    }
                };

                this.ws.onmessage = event => {
                    try {
                        const id = Math.random().toString().slice(2, 8)
                        const response = JSON.parse(event.data)
                        if (response.error !== 0) {
                            this.$notify({ 
                                title: '连接失败', 
                                message: response.message || '网络异常请稍后再试~', 
                                type: 'error', 
                                duration: 0 
                            })
                            return
                        }

                        that.bootTimeoutHandler()
                        if (response.message === 'success') {
                            const data = response.data?.trim?.('\n')?.trim?.('\r\n')?.replace?.('.",', '.')?.replace?.(' "', '')?.replace?.('"', '')?.replace?.('\\', '')
                            that.onSocketMessage({id, text: data})
                        }

                        if (response.message === 'articleDone') {
                            that.bootTimeoutHandler(true)
                            that.onSocketMessage({id, text: '', articleId: response.data?.id})
                        }
                    } catch (error) {
                        console.error('WebSocket message error:', error);
                        this.$notify({ 
                            title: '数据解析错误', 
                            message: '接收到无效数据，请刷新重试', 
                            type: 'error', 
                            duration: 0 
                        })
                    }
                };

                this.ws.onclose = function (event) {
                    console.log('连接关闭', event);
                    if (!event.wasClean && that.ws) {  // 添加 that.ws 检查
                        // 如果是非正常关闭，可以考虑重连
                        setTimeout(() => {
                            if (that.ws) {  // 再次检查 WebSocket 实例是否存在
                                that.initWebSocket();
                            }
                        }, 3000);
                    }
                };

                this.ws.onerror = e => {
                    console.error('WebSocket错误:', e);
                    that.$notify({ 
                        title: '系统异常', 
                        message: "WebSocket连接发生错误，请刷新页面重试", 
                        type: 'error', 
                        duration: 0 
                    })
                };
            } catch (error) {
                console.error('WebSocket initialization error:', error);
                this.$notify({ 
                    title: '连接错误', 
                    message: '无法建立WebSocket连接，请刷新页面重试', 
                    type: 'error', 
                    duration: 0 
                })
            }
        },
        bootTimeoutHandler(end = false) {
            const that = this;
            if (this.timeoutIndex) {
                clearTimeout(this.timeoutIndex);
                this.timeoutIndex = null
            }
            if (end) {
                return;
            }
            this.timeoutIndex = setTimeout(() => {
                that.ws.close();
                this.$msgbox.confirm('当前生成人数较多，请重新生成~', '响应超时', {
                    confirmButtonText: '确认',
                    cancelButtonText: '取消',
                    type: "warning",
                    showClose: false,
                    showCancelButton: false,
                    beforeClose: (action, instance, done) => {
                        if (action !== 'confirm') {
                            done()
                            return
                        }
                        setTimeout(() => {done();}, 500);
                        window.history.go(-1);
                    }
                })
            }, 30 * 1000);
        },
        toArticlePage() {
            if (this.confirmLoading) {return;}
            if (this.socketLoading) {
                this.$message.error('文章正在生成中~');
                return;
            }
            let params = {
                exerciseId: this.exerciseId,
                articleId: this.courseArticle?.id,
                userId: this.userId
            }
            this.confirmLoading = true
            startExercise(params).then(res => {
                this.confirmLoading = false
                if (res.error == 0) {
                    this.$router.push(`/aireading/info?exerciseId=${this.exerciseId}&userId=${this.userId}&articleId=${this.courseArticle?.id || ''}`);
                }else {
                    this.$notify({ title: '提示', message: res.msg, type: 'error', duration: 0 })
                }
            }).finally(() => {
                this.confirmLoading = false
            })
        },
        onSocketMessage(data) {
            switch(true) {
                case !!data.articleId: {
                    this.courseArticle.id = data.articleId;
                    setTimeout(() => {
                        this.paragraph.splice(this.paragraph.length - 1, 1);
                        this.isloading = false;
                        this.socketLoading = false;
                        
                    }, this.timerIndex * 50);
                    break;
                }
                
                case data.text === 'english' || this.keylist.length && this.keylist.length < 2: {
                    this.keylist.push(data.text);
                    break;
                }
                
                case this.keylist.length === 2: {
                    this.keystring = this.keylist.join('');
                    this.keylist = [];
                    break;
                }
                
                case this.keystring === 'english_' && !!data.text: {
                    if (data.text === '_') {
                        this.keystring = '';
                        setTimeout(() => {
                            this.paragraph.push({ text: 'line-feed' });
                            
                        }, this.timerIndex * 50);
                        return;
                    };
                    
                    ++this.timerIndex;
                    data.sign = this.requestQuery.words.includes(data.text.trim());
                    setTimeout(() => {
                        this.paragraph.push(data);
                        
                    }, this.timerIndex * 50);
                    break;
                }
            };
        }
    },
    destroyed() {
        // 组件销毁时确保 WebSocket 正确关闭
        this.closeWebSocket();
    }
}
</script>

<style scoped>
.cursor {
    display: inline-block;
    width: 10px;
    background-color: black;
    margin-left: 2px;
    animation: blink 0.7s infinite;
}
.filter-5{filter: blur(2px)}
@keyframes blink {
    0% { opacity: 1; }
    50% { opacity: 0; }
    100% { opacity: 1; }
}
</style>
